package com.hiyee.platform.util;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * excel 工具类
 *
 * @author WangBin
 */
public class ExcelUtil {
    /**
     * 读取本地 excel 文件
     *
     * @param filePath
     * @return
     * @throws IOException
     * @throws InvalidFormatException
     */
    public static List<Map<Integer, String>> read(String filePath) throws IOException, InvalidFormatException {

        File file = new File(filePath);
        List<Map<Integer, String>> dataList = new ArrayList<>();
        if(!file.exists()) {
            System.out.println("[Excel文件导入] " + filePath + "文件不存在！");
            return dataList;
        }
        // 读取 excel
        Workbook workbook = new XSSFWorkbook(file);
        Sheet sheet = workbook.getSheetAt(0);
        int firstRowIndex = sheet.getFirstRowNum() + 1;
        int lastRowIndex = sheet.getLastRowNum();

        for (int index = firstRowIndex; index <= lastRowIndex; index++) {
            Row row = sheet.getRow(index);

            if(row == null)continue;

            Map<Integer, String> rowData = new HashMap<>();
            for (int cIndex = 0; cIndex < row.getLastCellNum(); cIndex++) {
                Cell cell = row.getCell(cIndex);
                rowData.put(cIndex, cell.getStringCellValue());
            }
            dataList.add(rowData);
        }
        return dataList;
    }
}
